package app.yj.channel;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import java.util.Arrays;
import java.util.List;


import app.yj.channel.activity.WebViewActivity;
import app.yj.channel.entity.BlogResult;
import app.yj.channel.http.HttpBlog;
import app.yj.channel.http.HttpPool;
import app.yj.channel.strategy.BlogStrategy;
import app.yj.channel.strategy.PoolStrategy;
import tech.com.commoncore.utils.ApplicationUtil;
import tech.com.commoncore.utils.NetworkUtils;

/**
 * Time:2019/3/5
 * Desc: 渠道解析跳转管理.   针对leanCloud 建表处理.leancloud的开关跳转判断
 */
public class ChannelManager {

    /**
     * 发布渠道，和 productFlavors 对应
     */
    public static final String[] CHANNELS = {"vivo", "oppo", "mz", "lx", "qh360", "yyb", "yyh", "sg", "jl", "hw", "mi"};
    public static final String[] GROUPS = {"jf", "sd", "lt", "tko", "tks"}; // 开发小组组名 17楼-->闪电(sd)    6楼-->疾风(jf)  后期根据小组增加添加.

    public static final String TABLE_SWITCH = "CheckVersion";
    public static final String SWITCH_NEED_SWITCH = "versionCode";   // 0/空：正常界⾯面，1： 跳转到H5的界⾯面；
    public static final String SWITCH_URL = "versionUrl";
    public static final String SWITCH_TOOLBAR_COLOR = "versionBg";   //为H5界⾯面状态栏⽂文字颜⾊色，输⼊入以 0x 开头的颜⾊色 如0x000000代表⿊黑⾊色
    public static final String SWITCH_NAVIGATION_COLOR = "versionCol"; //(无用字段) 字段为H5界⾯面导航栏背景⾊色，输⼊入以 0x 开头的颜⾊色 如0x000000代表⿊黑⾊色；
    public static final String SWITCH_NAME = "name";

    public static boolean isRequest = false;

    /**
     * @param context  启动页对应的Activity
     * @param appName  根据自己App信息进行传（应用简称+月日）
     * @param callback
     */
    public static void request(final Activity context, final String appName, @NonNull final ICallback callback) {
        // 1. 检查网络是否正常，不正常： 进到网络异常提示页，可点击重新加载
        if (!NetworkUtils.isNetworkConnected()) {
            callback.showNetWorkError();
            return;
        }

        ChannelCache.setIsFinishBrowerAndGoApp(false);

        //2. 网络正常 则检查是否存在缓存
        BlogResult cacheBlogResult = ChannelCache.getBlogResult(context);

        if (cacheBlogResult == null) {
            //无缓存，访问内置的接口地址获取 地址池 并缓存进本地。
            doRequest(context, appName, initBlogResult(), callback);
        } else {
            //有缓存，检查开关
            if (cacheBlogResult.getStatus() == 1 && !TextUtils.isEmpty(cacheBlogResult.getUrl())) {
                // 开关 是打开状态 进 WebViewActivity 加载url
                context.startActivity(WebViewActivity.actionToActivity(context, cacheBlogResult.getUrl(), cacheBlogResult.getBlackOrWhite(), cacheBlogResult.getVersionCol()));
            }
            doRequest(context, appName, cacheBlogResult, callback);
        }


    }

    /**
     * 获取缓存默认值
     *
     * @return
     */
    private static BlogResult initBlogResult() {
        return new BlogResult(Arrays.asList(Config.dPoolList), Arrays.asList(Config.fPoolList), Arrays.asList(Config.dBlogList), Arrays.asList(Config.fBlogList));
    }

    public static void doRequest(final Context context, final String name, final BlogResult blogResult, @NonNull final ICallback callback) {
        if ((blogResult.getdPool().size() > 0) || (blogResult.getfPool().size() > 0)) {
            //国内外域名不同时为空情况下请求国内外域名
            requestPools(context, name, blogResult, callback);
        } else if ((blogResult.getdBlog().size() > 0) || (blogResult.getfBlog().size() > 0)) {
            //国内外Blog不同时为空情况下请求国内外Blog
            requestBlogs(context, name, blogResult, callback);
        } else {
            //当所有地址都为空时，重新请求初始
            doRequest(context, name, initBlogResult(), callback);
            //            callback.goApp();
        }
    }

    /**
     * 请求国内外域名地址池
     *
     * @param context
     * @param name
     * @param blogResult
     * @param callback
     */
    public static void requestPools(final Context context, final String name, final BlogResult blogResult, @NonNull final ICallback callback) {
        PoolStrategy strategy = new PoolStrategy(blogResult.getdPool().size(), blogResult.getfPool().size(), new PoolStrategy.IRequestCallBack() {
            @Override
            public void requestBlog() {
                if (!isRequest) {
                    //所有博客请求失败情况下,回调重新发起博客请求
                    requestBlogs(context, name, blogResult, callback);
                    isRequest = true;
                } else {
                    //缓存数据
                    BlogResult cacheBlogResult = ChannelCache.getBlogResult(context);
                    if ((cacheBlogResult != null) && (cacheBlogResult.getStatus() == 1) && !TextUtils.isEmpty(cacheBlogResult.getUrl())) {
                        //如果当前缓存已跳转,则不做操作
                        ((Activity) context).finish();
                    } else {
                        callback.goApp();
                    }
                    //                    if ((cacheBlogResult != null) && (cacheBlogResult.getStatus() == 1)) {
                    //                        //如果缓存已为开,需先关闭后打开
                    //                        ChannelCache.setIsFinishBrowerAndGoApp(true);
                    //                        BusManager.getBus().post(new FinishBrowerEvent());
                    //                    }
                    //                    callback.goApp();
                }

            }
        });
        requestPool(context, blogResult.getdPool(), PoolStrategy.TYPE_HTTP_DPOOL, name, callback, strategy);//请求国内域名池
        requestPool(context, blogResult.getfPool(), PoolStrategy.TYPE_HTTP_FPOOL, name, callback, strategy);//请求国外域名池
    }

    /**
     * 请求博客地址池
     *
     * @param context
     * @param name
     * @param blogResult
     * @param callback
     */
    public static void requestBlogs(final Context context, final String name, BlogResult blogResult, @NonNull final ICallback callback) {

        BlogStrategy strategy = new BlogStrategy(blogResult.getdBlog().size(), blogResult.getfBlog().size(), new BlogStrategy.IRequestCallBack() {
            @Override
            public void requestFail() {
                //所有请求都失败
                BlogResult cacheBlogResult = ChannelCache.getBlogResult(context);
                if ((cacheBlogResult != null) && (cacheBlogResult.getStatus() == 1) && !TextUtils.isEmpty(cacheBlogResult.getUrl())) {
                    //如果当前缓存已跳转,则不做操作
                    ((Activity) context).finish();
                    //                    //如果当前缓存已跳转
                    //                    ChannelCache.setIsFinishBrowerAndGoApp(true);
                    //                    BusManager.getBus().post(new FinishBrowerEvent());
                    //                    callback.goApp();
                } else {
                    callback.goApp();
                }
            }
        });
        HttpBlog.IBlogCallback blogCallback = new HttpBlog.IBlogCallback() {
            @Override
            public void newRequest(BlogResult blogResult) {
                requestPools(context, name, blogResult, callback);
                //                if (!isRequest) {
                //                    //博客请求成功情况下回调重新发起请求
                //                    requestPools(context, name, blogResult, callback);
                //                    isRequest = true;
                //                } else {
                //                    //缓存数据
                //                    BlogResult cacheBlogResult = ChannelCache.getBlogResult(context);
                //                    if ((cacheBlogResult != null) && (cacheBlogResult.getStatus() == 1)) {
                //                        //如果缓存已为开,需先关闭后打开
                //                        ChannelCache.setIsFinishBrowerAndGoApp(true);
                //                        BusManager.getBus().post(new FinishBrowerEvent());
                //                    }
                //                    callback.goApp();
                //                }

            }
        };
        requestBlog(blogResult.getdBlog(), BlogStrategy.TYPE_HTTP_DBLOG, blogCallback, strategy);
        requestBlog(blogResult.getfBlog(), BlogStrategy.TYPE_HTTP_FBLOG, blogCallback, strategy);
    }

    /**
     * 请求域名地址
     */
    private static void requestPool(Context context, List<String> poolList, String type, String name, @NonNull ICallback callback, PoolStrategy strategy) {
        if (poolList != null) {
            for (int i = 0; i < poolList.size(); i++) {
                String link = poolList.get(i);
                HttpPool.requestTableSwitch(context, link, type, name, callback, strategy);
            }
        }
    }

    /**
     * 请求博客地址
     */
    private static void requestBlog(List<String> blogList, String type, @NonNull HttpBlog.IBlogCallback blogCallback, BlogStrategy strategy) {
        if (blogList != null) {
            for (int i = 0; i < blogList.size(); i++) {
                String link = blogList.get(i);
                HttpBlog.requestTableSwitch(link, type, blogCallback, strategy);
            }
        }
    }

    /**
     * 获取渠道码
     *
     * @param appName
     * @return
     */
    public static String getChannelCode(Context context, String appName) {
        if (appName == null || appName.equals("")) {
            throw new RuntimeException("请传入应用缩写");
        }
        return appName + ApplicationUtil.getMetaValueFromApp(context, "UMENG_CHANNEL");
    }


    /**
     * 开关校验后的回调.
     */
    public interface ICallback {
        void showNetWorkError();

        void goApp();
    }

}